package com.key.sys.privilege;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.springframework.web.servlet.ModelAndView;

import com.key.model.User;
import com.key.tools.ConnectionPool;

public class SystemPrivilege {

	private User user = null;
	private SystemPrivilegePK spp = null;

	public SystemPrivilege(User user,SystemPrivilegePK spp){
		this.user = user;
		this.spp = spp;
	}
	/**
	 * 判断是否有权限
	 * @return
	 */
	public boolean isPremission(){
		boolean flag = false;
		ConnectionPool cp = ConnectionPool.getInstance();
		Connection ct = cp.getConnection();
		try{
			PreparedStatement ps = ct.prepareStatement("select group_id,code from t_user u left join t_group g on u.group_id = g.id where username = ?");
			ps.setString(1, user.getLoginName());
			ResultSet rs = ps.executeQuery();
			String groupid = "";
			String code = "";
			if(rs.next()){
				groupid = rs.getString("group_id");
				code = rs.getString("code");
			}
			rs.close();
			ps.close();
			
			if(code.equals("admin")){
				return true;
			}
			
			PreparedStatement ps2 = ct.prepareStatement("select module,action,group_id from t_premission where module = ? and action=?");
			ps2.setString(1, spp.getModule());
			ps2.setString(2, spp.getPrivilege());
			ResultSet rs2 = ps2.executeQuery();
			int count = 0;
			while(rs2.next()){
				String group = rs2.getString("group_id");
				if(group.equals(groupid)){
					flag = true;
					break;
				}
				count++;
			}
			if(count==0){
				flag = true;
			}
			rs2.close();
			ps2.close();
		}catch(Exception e){
			return false;
		}finally{
			try{
			ct.close();
			}catch(Exception e){
				return false;
			}
		}
		return flag;
	}
}
